package com.bawei.module_live.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.mvi.base.BaseViewModel
import com.bawei.module_live.intent.LiveIntent
import com.bawei.module_live.repository.LiveRepository
import com.bawei.module_live.state.LiveState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch

class LiveViewModel : BaseViewModel<LiveIntent>() {
    private val repository: LiveRepository by lazy { LiveRepository() }

    private var liveFlow = MutableStateFlow<LiveState>(LiveState.Init)

    val liveFlow_ = liveFlow.asStateFlow()

    // 根据意图发起网络请求
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {
                    is LiveIntent.GetVideo -> getVideoData(
                        page = it.page,
                        pageSize = it.pageSize
                    )
                    is LiveIntent.GetGoodsList -> getGoodsListData(
                        it.categoryId, it.currentPage, it.pageSize, it.roomId
                    )
                }
            }
        }
    }

    // 根据网络请求结果更新状态流
    private fun getVideoData(page: Int, pageSize: Int) {
        viewModelScope.launch {
            liveFlow.value = LiveState.Loading
            repository.getVideo(page, pageSize)
                .catch { e ->
                    liveFlow.value = LiveState.Failed(e.message.toString())
                }
                .filter {
                    it != null
                }
                .collect {
                    if (it.code == 200) {
                        if (it.data.isEmpty()) {
                            liveFlow.value = LiveState.Empty
                        } else {
                            liveFlow.value = LiveState.Success(it.data)
                        }
                    } else {
                        liveFlow.value = LiveState.Failed(it.msg)
                    }
                }
        }
    }

    private fun getGoodsListData(categoryId: Int, currentPage: Int, pageSize: Int, roomId: Int) {
        viewModelScope.launch {
            repository.getGoodsList(categoryId, currentPage, pageSize, roomId)
                .catch { e ->
                    liveFlow.value = LiveState.GoodsListFailed(e.message.toString())
                }
                .collect {
                    if (it.code == 200) {
                        liveFlow.value = LiveState.GoodsListSuccess(it.data)
                    } else {
                        liveFlow.value = LiveState.GoodsListFailed(it.msg)
                    }
                }
        }
    }

    fun resetState() {
        liveFlow.value = LiveState.Init
    }
} 